<script setup>
import * as Api from '@/api/tiku.js'
import { ref, onMounted } from 'vue';
import {Upload} from "@element-plus/icons-vue";
import {ElMessage, ElMessageBox} from "element-plus";
const products = ref([])
const title =ref('')
const type =ref('')
const year =ref('')
const liulan =async (id)=>{
  let result = await Api.find(id)
  if (result.code === 200){
    console.log(result)
  }
}
function logProduct(product) {
  console.log(product); // 在控制台打印产品信息
  drawer.value = true
  liulan(product.id)
}
const loading = ref(false)
const error = ref(null);
// 定义一个异步函数来获取商品列表
const fetchProducts = async () => {
  try {
    // const response = await axios.get('http://your-backend-api/products');
    // products.value = response.data;
  } catch (err) {
    error.value = '加载商品列表时出错';
  } finally {
    loading.value = false
  }
};
const dialogVisible = ref(false)
const currentPage =ref(1)
const pageSize =ref(100)
const getData =async ()=> {
  let result = await Api.page({
    "pageSize": pageSize.value,
    "currentPage": currentPage.value,
    "title":title.value,
    "type":type.value,
  })
  if (result.code === 200){
    products.value = result.data.rows
  }
}
const shuaxin = async ()=> {
  title.value = '';
  type.value = '';
  let result = await Api.page({
    "title":'',
    "type":'',
  })
  if (result.code === 200){
    products.value = result.data.rows
  }
}
const find =async (type)=>{
  let result = await Api.page({
    "type": type,
  })
  if (result.code === 200){
    products.value = result.data.rows
  }
}
onMounted(async () => {
  await getData()
  // await fetchProducts()
})
const form = ref({
  title :'',
  type: '',
  year: '',
  answer: '',
})
const add = async () => {
  let result = await Api.upload({
    "title" :  form.value.title,
    "type": form.value.type,
    "year": form.value.year,
    "answer":form.value.answer,
    "file": formData
  })
  if(result.code === 200){
    getData()
    dialogVisible.value=false
    ElMessage.success(result.message)
  }else {
    ElMessage.error(result.message)
  }
}
const submit = ()=> {
  uploadFile()
  add()
}
let isAdd = ref(true)
// const handleClose = (done: () => void) => {
//   ElMessageBox.confirm('您确定取消操作?')
//       .then(() => {
//         done()
//       })
//       .catch(() => {
//         // catch error
//       })
// }
const btuAdd =() => {
  dialogVisible.value = true
}
const dele = async (id) => {
  try {
    let result = await Api.dele(id); // 假设 Api.dele 返回一个 Promise
    if (result.code === 200) {
      // 如果需要立即更新本地列表，取消注释下一行
      updateLocalProducts(id); // 一个假设的函数，用于更新本地商品列表
      ElMessage.success(result.message);
    } else {
      ElMessage.error(result.message);
    }
  } catch (error) {
    console.error('删除商品时出错:', error);
    ElMessage.error('删除商品时出错，请稍后再试。');
  }
};
// const handleFileUpload = (event) => {
//
//   const file = event.target.files[0];
//   if (file) {
//     const reader = new FileReader();
//     // 当文件读取完成时，将结果设置为audioBase64的值
//     reader.onload = (e) => {
//       audioBase64.value = e.target.result;
//       form.value.audio = audioBase64.value
//     };
//     // 读取文件内容并将其编码为Base64
//     reader.readAsDataURL(file);
//   }
//
// };
const drawer = ref(false)
const selectedProducts = ref([]); // 选中商品的 ID 数组
console.log(selectedProducts.value)
async function deleteSelectedProducts() {
  try {
    for (const productId of selectedProducts.value) {
      await dele(productId); // 等待每个删除操作完成
      // 如果需要立即更新本地列表，取消注释下一行（但通常不推荐这样做）
      // products.value = products.value.filter(product => product.id !== productId);
    }
    selectedProducts.value = []; // 清空选中状态
    // 可选：显示成功消息或执行其他成功后的逻辑
    ElMessage.success('已删除选中的商品。');
  } catch (error) {
    console.error('删除选中商品时出错:', error);
    // 重置选中状态或给用户一个错误提示（这里已经由 dele 函数内的 catch 块处理了单个删除的错误）
  }
}
// 假设的更新本地商品列表的函数（如果需要的话）
function updateLocalProducts(id) {
  products.value = products.value.filter(product => product.id !== id);
}
const options = [
  {
    value: '六级',
    label: '六级',
  },
  {
    value: '四级',
    label: '四级',
  },
]
const handleTypeChange = (selectedValue) => {
  console.log('当前选中题型值:', selectedValue)
  console.log('当前响应式变量值:', type.value)
  find(selectedValue)
  // 调用您的业务方法
}
const options1 = [
  {
    value: '2026/12',
    label: '2026/12',
  },
  {
    value: '2026/6',
    label: '2026/6',
  },
  {
    value: '2025/12',
    label: '2025/12',
  },
  {
    value: '2025/6',
    label: '2025/6',
  },
  {
    value: '2024/12',
    label: '2024/12',
  },
  {
    value: '2024/6',
    label: '2024/6',
  },
  {
    value: '2023/12',
    label: '2023/12',
  },
  {
    value: '2023/6',
    label: '2023/6',
  },
  {
    value: '2022/12',
    label: '2022/12',
  },
  {
    value: '2022/6',
    label: '2022/6',
  },
  {
    value: '2021/12',
    label: '2021/12',
  },
  {
    value: '2021/6',
    label: '2021/6',
  },
  {
    value: '2020/12',
    label: '2020/12',
  },
  {
    value: '2020/6',
    label: '2020/6',
  },
]
const file = ref(null);
const message = ref('');
const url = ref("")
const look =ref(false);
const uploadf = async () => {
  if (!file.value) {
    alert('请选择文件！');
    return;
  }
  const formData = new FormData();
  formData.append('file', file.value);
  try {
    const response = await Api.uploadfile( formData)
    if (response.code === 200){
      url.value = response.message
      look.value = true
    }
    await getData()
  } catch (error) {
    ElMessage.error('上传失败:', error);
  }
};
const handleFileChange = (event) => {
  file.value = event.target.files[0]; // 获取选择的文件
  uploadf()
};
const formData = new FormData();
const uploadFile = async () => {
  if (!file.value) {
    alert('请选择文件！');
    return;
  }
  const formData = new FormData();
  formData.append('file', file.value);
  formData.append('title', form.value.title); // 根据需要填写
  formData.append('type', form.value.type); // 根据需要填写
  formData.append('year', form.value.year); // 根据需要填写，或动态获取
  formData.append('answer', form.value.answer); // 根据需要填写，或动态获取

  try {
    const response = await Api.upload( formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });
    ElMessage.success('上传成功:', response.data);
    dialogVisible.value = false
    await getData()
  } catch (error) {
    ElMessage.error('上传失败:', error);
  }
};
function lookfile() {
  console.log(url.value)
  window.open(url.value, '_blank');
}
</script>

<template>
    <div style="position: absolute;top: 60px;width: 90%;height: 60px;border-bottom: solid 1px rgb(221.7, 222.6, 224.4);margin: auto;padding-top: 20px">
      <el-row>
        <el-col :span="8">
          <el-button style="
        border: solid 1px #4285F4;
        border-radius: 20px;
        width: 150px;
        color: #4285F4;
        background-color:rgb(216.8, 235.6, 255);"
                     @click="btuAdd"
          >
            上传题库<el-icon class="el-icon--right"><Upload /></el-icon>
          </el-button>
          <button style="
        border: solid 1px rgb(196, 86.4, 86.4);
        border-radius: 20px;
        width: 150px;
        height: 32px;
        color: rgb(196, 86.4, 86.4);
        margin-left: 10px;
        background-color:rgb(254, 240.3, 240.3);"
                  @click="deleteSelectedProducts">删除选中</button>
          <div class="grid-content ep-bg-purple" />
        </el-col>
        <el-col :span="8">
          <div class="grid-content ep-bg-purple-light" />
        </el-col>
        <el-col :span="8">
          <el-input
              v-model="title"
              style="width: 200px;padding-left: 5px;border-radius: 20px ;margin-right: 5px"
              placeholder="请输入名称:"
          />
            <el-select
                v-model="type"
                placeholder="请选择类别："
                size="default"
                style="width: 200px;height:20px;min-height: 20px;margin-right: 5px;margin-bottom: 15px"
                @change="handleTypeChange"
            >
              <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              />
            </el-select>
<!--          <el-input-->
<!--              v-model="type"-->
<!--              style="width: 200px;padding-left: 5px;border-radius: 20px ;margin-right: 5px"-->
<!--              placeholder="请输入类型："-->
<!--          />-->
          <el-button @click="getData" style="border: solid 1px #4285F4;border-radius: 20px;width: 20px;color: #4285F4;background-color:rgb(216.8, 235.6, 255);">
            <el-icon class="el-icon--right"><el-icon><Search /></el-icon></el-icon>
          </el-button>
          <el-button style="border: solid 1px #4285F4;border-radius: 20px;width: 20px;color: #4285F4;background-color:rgb(216.8, 235.6, 255);" @click="shuaxin">
            <el-icon ><el-icon><RefreshRight /></el-icon></el-icon>
          </el-button>
          <div class="grid-content ep-bg-purple" />
        </el-col>
      </el-row>
    </div>
    <div style="margin-top:60px" >
      <div style="height:660px ;width: 100%">
        <el-scrollbar height="660px;">
          <div style="width: 100%;height: 500px" class="product-list">
            <div v-if="loading">加载中...</div>
            <div v-else-if="error">{{ error }}</div>
            <div v-else class="product-grid">
              <div @click="logProduct(product)" v-for="product in products" :key="product.id" class="product-box">
                <input
                    type="checkbox"
                    v-model="selectedProducts"
                    :value="product.id"
                    style="margin-left: 140px;padding-bottom: 15px;width: 20px;height: 20px"
                />
                <div style="background-color:black;height: 120px;width:175px;position:relative;top: 70px;opacity: 0.6" class="wenjian">

                  <h2 style="position: relative;width:175px;top: 50px;color: white;font-size: 1.1rem;
    line-height: 1; ">{{ product.title }}</h2>
                </div>
<!--                <h2 style="position: relative;width:50px;top: 90px;color: white;font-size: 0.9rem;-->
<!--    line-height: 1; ">{{ product.type }}</h2>-->

              </div>
            </div>
          </div>
        </el-scrollbar>
      </div>
      <el-dialog
          v-model="dialogVisible"
          :title="isAdd ? '新增:' : '修改:'"
          width="30%"
          style="height: 500px;"
          :before-close="handleClose"
      >
        <div style="width: 100% ; border-top: #6b778c 1px solid;margin-bottom: 50px"></div>
      <span>
        <el-form  label-width="auto" :model="form" class="demo-form-inline" style="margin-left: 50px">
    <el-form-item label="作业标题：">
      <el-input v-model="form.title" style="width: 260px"  />
    </el-form-item>
    <el-form-item label="类别：">
      <el-select
          v-model="form.type"
          placeholder="请选择"
          size="default"
          style="width: 260px;height:20px;min-height: 20px;margin-right: 5px;margin-bottom: 15px"
      >
          <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
    </el-form-item>
          <el-form-item label="年份：">
      <el-select
          v-model="form.year"
          placeholder="请选择"
          size="default"
          style="width: 260px;height: 20px;min-height: 20px;margin-right: 5px;margin-bottom: 15px"
          @change="handleYearChange"
      >
          <el-option
              v-for="item in options1"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
    </el-form-item>
    <el-form-item label="试卷答案：">
        <el-mention
            v-model="form.answer"
            type="textarea"
            style="width: 320px"
            placeholder="请输入答案"
        />
    </el-form-item>
          <el-form-item label="文件上传：">
            <div class="file-upload">
    <label class="upload-button" for="fileInput">
      <span>选择 PDF 文件</span>
      <!-- 隐藏的文件输入 -->
      <input type="file" id="fileInput" accept="application/pdf" @change="handleFileChange" />
    </label>
           <!-- 这里可以添加其他内容，比如上传后的文件预览 -->
  </div>
  <el-button v-show="look" @click="lookfile" style="height: 35px">
         查看文件
       </el-button>
            <!--        <input type="file" @change="handleFileChange" accept="application/pdf"  />-->
    </el-form-item>
          <el-button @click="uploadFile()"
                     style="
                     border: solid 1px #4285F4;
                     border-radius: 20px;
                     width: 100px;
                     color: #4285F4;
                     margin-left: 300px">提交</el-button>
  </el-form>
      </span>
      </el-dialog>
    </div>


<!--  <el-drawer v-model="drawer" title="在线浏览" size="50%">-->



<!--  </el-drawer>-->


</template>

<style scoped>
.product-box {
  border: 1px solid #ccc;
  padding: 16px;
  margin: 16px 0;
  width: 200px;
  height: 250px;
  background-color: pink;
  background-image: url('@/image/tk.webp');
  background-repeat: no-repeat;
  background-size: 100% 100%;
}
.scrollbar-demo-item {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 50px;
  margin: 10px;
  text-align: center;
  border-radius: 4px;
  background: var(--el-color-primary-light-9);
  color: var(--el-color-primary);
}
.product-list {
  max-width: 1600px; /* 可选：限制列表的最大宽度 */
//margin: 0 auto;   /* 可选：使列表居中 */
  padding: 20px;    /* 可选：为列表添加内边距 */
}

.product-grid {
  display: flex;
  flex-wrap: wrap; /* 允许子元素换行 */
  gap: 30px;       /* 子元素之间的间距 */
}

.product-box {
  width: 185px;    /* 固定宽度 */
  height: 220px;
  box-sizing: border-box; /* 包括内边距和边框在内计算元素的总宽度和高度 */
  border: 1px solid #ccc;
  padding: 16px;
  text-align: center; /* 可选：使文本居中 */
  overflow: hidden;   /* 可选：隐藏超出盒子大小的内容 */
}
@media (max-width: 1760px) { /* 稍微大一点以确保8个盒子能在一行内（考虑边框、内边距等） */
  .product-grid {
    flex-wrap: wrap; /* 允许换行 */
  }

  .product-box {
    /* 你可以在这里设置更小的宽度或百分比宽度，以适应更小的屏幕 */
    /* 例如：width: calc(25% - 20px); 在四列布局时使用 */
  }
}
.card {
  position: absolute;
  width: 100%;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.8);
  text-align: left;
}
.product-box:hover {
  box-shadow: 0 4px 5px rgba(0, 0, 0, 0.2); /* 鼠标经过时的阴影效果 */
}
.wenjian:hover {
  box-shadow: 0 10px 15px rgba(0, 0, 0, 0.2);
}
.custom-file-upload {
  padding-bottom: 40px;
  text-align: center;
  height: 30px;
  width: 150px;
  display: inline-block;
  border: solid 1px #4285F4;
  border-radius: 20px;
  color: #4285F4;
  background-color:rgb(216.8, 235.6, 255);
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.custom-file-upload:hover {
  background-color: white;
}
.file-upload {
  text-align: center;
  margin: 20px;
}

.upload-button {
  display: inline-block;
  //padding: 10px 10px;
  width: 100px;
  height: 35px;
  font-size: 14px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s ease;
  position: relative;
  overflow: hidden;
  text-align: center;
}

.upload-button span {
  display: block;
}

.upload-button input[type="file"] {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  opacity: 0;
  cursor: pointer;
}

.upload-button:hover {
  background-color: #0056b3;
}
</style>